package com.xiao.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiao.train.business.domain.Train;
import com.xiao.train.business.domain.TrainExample;
import com.xiao.train.business.resp.TrainQueryResp;
import com.xiao.train.common.resp.PageResp;
import com.xiao.train.common.util.SnowUtil;
import com.xiao.train.business.resp.StationQueryResp;
import com.xiao.train.business.domain.Station;
import com.xiao.train.business.domain.StationExample;
import com.xiao.train.business.mapper.StationMapper;
import com.xiao.train.business.req.StationQueryReq;
import com.xiao.train.business.req.StationSaveReq;
import lombok.extern.slf4j.Slf4j;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class StationService {

    @Resource
    StationMapper stationMapper;

    public void save(StationSaveReq req) {
        DateTime now = DateTime.now();
        Station station = BeanUtil.copyProperties(req, Station.class);
        if (ObjectUtil.isNull(station.getId())) {
            station.setId(SnowUtil.getId());
            station.setCreateTime(now);
            station.setUpdateTime(now);
            stationMapper.insert(station);
        } else {
            station.setUpdateTime(now);
            stationMapper.updateByPrimaryKey(station);
        }
    }
    public PageResp<StationQueryResp> queryList(StationQueryReq req) {
        StationExample stationExample = new StationExample();
        StationExample.Criteria criteria = stationExample.createCriteria();
        stationExample.setOrderByClause("id desc");
        log.info("查询页码: {}", req.getPage());
        log.info("每页条数: {}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Station> stations = stationMapper.selectByExample(stationExample);

        PageInfo<Station> pageInfo = new PageInfo<>(stations);
        log.info("总行数: {}", pageInfo.getTotal());
        log.info("总页数: {}", pageInfo.getPages());

        PageResp<StationQueryResp> pageResp = new PageResp<>();
        List<StationQueryResp> list = BeanUtil.copyToList(stations, StationQueryResp.class);
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        stationMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public List<StationQueryResp> queryAll() {
        List<Station> stations = selectAll();
        return BeanUtil.copyToList(stations, StationQueryResp.class);
    }

    public List<Station> selectAll() {
        StationExample stationExample = new StationExample();
        return stationMapper.selectByExample(stationExample);
    }
}
